package com.stylefeng.guns.modular.yjya.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.constant.state.CounterplanStatus;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.Tip;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.yjya.dao.AccidentDao;
import com.stylefeng.guns.modular.yjya.dao.CounterplanDao;
import com.stylefeng.guns.modular.yjya.dao.EmergencypropertyDao;
import com.stylefeng.guns.modular.yjya.service.*;
import com.stylefeng.guns.modular.yjya.warpper.CounterplanTemplateWarpper;
import com.stylefeng.guns.modular.yjya.warpper.CounterplanWarpper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author xuziyang
 * @Date 2018-01-18 15:54:06
 */
@Controller
@RequestMapping("/counterplan")
@Slf4j
public class CounterplanController extends BaseController {

    private String PREFIX = "/yjya/counterplan/";

    @Autowired
    private ICounterplanService counterplanService;

    @Autowired
    private ICounterplanTemplateService counterplanTemplateService;

    @Autowired
    private CounterplanDao counterplanDao;

    @Autowired
    private AccidentDao accidentDao;

    @Autowired
    private ICounterplanProcessService counterplanProcessService;

    @Autowired
    private IAccidentEmergencypropertyService accidentEmergencypropertyServicee;

    @Autowired
    private EmergencypropertyDao emergencypropertyDao;

    @Autowired
    private ICounterplanTypeTemplateService counterplanTypeTemplateService;


    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "counterplan.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/counterplan_add")
    public String counterplanAdd(@RequestParam("templateId")Integer templateId,Model model) {
        CounterplanTemplate template =  counterplanTemplateService.selectById(templateId);
        Map<String, Object> templateMap = BeanKit.beanToMap(template);
        model.addAttribute("template", new CounterplanTemplateWarpper(templateMap).warp());
        return PREFIX + "counterplan_add.html";
    }

    /**
     * 菜单预案编辑跳转页面
     */
    @RequestMapping("/counterplan_add_edit")
    public String counterplanAddEdit(Model model) {
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        return PREFIX + "counterplan_add_edit.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/counterplan_update/{counterplanId}")
    public String counterplanUpdate(@PathVariable Integer counterplanId, Model model) {
        Wrapper wrapper = new EntityWrapper<Counterplan>();
        wrapper.eq("id", counterplanId);
        Map<String,Object> map = counterplanService.selectMap(wrapper);
        model.addAttribute("item",new CounterplanWarpper(map).warp());
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        return PREFIX + "counterplan_edit.html";
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public Object getAll() {
        List<Map<String,Object>> list = counterplanService.selectMaps(null);
        return new CounterplanWarpper(list).warp();
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "name",required = false)String name
            ,@RequestParam(value = "type",required = false) String type
            ,@RequestParam(value = "level",required = false) String level
            ,@RequestParam(value = "accidentTypeId",required = false) Integer accidentTypeId) {
        Page<Counterplan> page = new PageFactory<Counterplan>().defaultPage();
        List<Map<String, Object>> result = counterplanDao.getCounterplans(page, name, type, level,accidentTypeId);
        page.setRecords((List<Counterplan>) new CounterplanWarpper(result).warp());
        return super.packForBT(page);
    }


    /**
     * 获取接警匹配的预案及历史案例列表
     */
    @RequestMapping(value = "/listSel")
    @ResponseBody
    public Object listSel(@RequestParam(value = "name",required = false)String name
            ,@RequestParam(value = "type",required = false) String type
            ,@RequestParam(value = "level",required = false) String level
            ,@RequestParam(value = "accidentTypeId",required = false) Integer accidentTypeId
            ,@RequestParam(value = "emergencyId",required = false) Integer emergencyId
            ,@RequestParam(value = "emergencyproId",required = false) Integer emergencyproId) {
        Page<Counterplan> page = new PageFactory<Counterplan>().defaultPage();
        Page<Accident> pageAccident = new PageFactory<Accident>().defaultPage();
        List<Map<String, Object>> result = counterplanDao.getCounterplansHandle(page, name, type, level,accidentTypeId);
        List<Map<String, Object>> reuttAccident = accidentDao.getAccident(pageAccident,emergencyId);
        for(int i = 0;i<reuttAccident.size();i++){
            //并集
            double union = 0;
            //交集
            double intersection = 0;
            //获取实体类型的所有属性
            Field[] field = AccidentEmergencyproperty.class.getDeclaredFields();
            if(emergencyId!=null){
                //获得相关突发事件类型的权重
                Emergencyproperty emergencyproperty = emergencypropertyDao.getEmergencyPropertyOne(emergencyId);
                if(reuttAccident.get(i).get("emergencyproId")!=null){
                    //历史案例的突发事件属性值
                    AccidentEmergencyproperty accidentEmergencyproperty = accidentEmergencypropertyServicee.selectById((Integer) reuttAccident.get(i).get("emergencyproId"));
                    //接警时输入的值
                    AccidentEmergencyproperty accidentEmergencyproperty1 = accidentEmergencypropertyServicee.selectById(emergencyproId);
                    for(int j =0;j<field.length;j++){
                        if(field[j].getName()!="id" &&field[j].getName()!="serialVersionUID"){

                            if((!invokeGet(accidentEmergencyproperty, field[j].getName()).toString().equals(""))&&(invokeGet(accidentEmergencyproperty1, field[j].getName())!=null)){
                                System.out.println("==============================="+j);
                                intersection = intersection + Double.parseDouble(invokeGet(emergencyproperty, field[j].getName()).toString());
                            }
                            else if((!invokeGet(accidentEmergencyproperty, field[j].getName()).toString().equals(""))&&(invokeGet(accidentEmergencyproperty1, field[j].getName())==null)){
                                union = union + intersection + Double.parseDouble(invokeGet(emergencyproperty, field[j].getName()).toString());
                            }
                            else if((invokeGet(accidentEmergencyproperty, field[j].getName()).toString().equals(""))&&(invokeGet(accidentEmergencyproperty1, field[j].getName())!=null)){
                                union = union + intersection + Double.parseDouble(invokeGet(emergencyproperty, field[j].getName()).toString());
                            }
                            else{
                                continue;
                            }
                        }
                        continue;
                    }
                }
            }
            NumberFormat nf=NumberFormat.getNumberInstance() ;
            nf.setMaximumFractionDigits(2);
            if(union!=0){
                //设置接警与历史案例的匹配度
                reuttAccident.get(i).put("similarity",nf.format(intersection/union));
            }
            else{
                //设置接警与历史案例的匹配度
                reuttAccident.remove(i);
            }

        }
        result.addAll(reuttAccident);
        page.setRecords((List<Counterplan>) new CounterplanWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 编制预案时处置流程选择
     * @return
     */
    @RequestMapping("/process_sel")
    public String counterplanProcessSel() {
        return PREFIX + "counterplan_process_sel.html";
    }

    /**
     * 修改预案时处置流程选择
     * @return
     */
    @RequestMapping("/editprocess_sel")
    public String counterplanEditProcessSel() {
        return PREFIX + "counterplan_edit_process_sel.html";
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Counterplan counterplan ,@RequestParam(value = "processIds[]",required = false) String[] processIds) {
        counterplanService.insert(counterplan,processIds);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") List<Integer> ids) {
        counterplanService.deleteBatchIds(ids);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Counterplan counterplan,@RequestParam(value = "processIds[]",required = false) String[] processIds) {
        log.debug(Arrays.toString(processIds));
        counterplanService.updateById(counterplan,processIds);
        return super.SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{counterplanId}")
    public Object detail(@PathVariable("counterplanId") Integer counterplanId, Model model) {
        Counterplan cunterplan = counterplanService.selectById(counterplanId);
        if(cunterplan == null){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("content",cunterplan.getContent());
        List<CounterplanTypeTemplate> counterplanTypeTemplateList = counterplanTypeTemplateService.selectList(null);
        model.addAttribute("counterplantypes",counterplanTypeTemplateList);
        return PREFIX + "counterplan_detail.html";
    }

    @RequestMapping("/process/{id}")
    @ResponseBody
    public Object getProcess(@PathVariable("id") Integer id) {
        return counterplanProcessService.selectProcesses(id);
    }

    /**
     * 审核通过
     */
    @RequestMapping("/approve")
    @ResponseBody
    public Tip freeze(@RequestParam(value = "ids[]") List<Integer> ids) {

        List<Counterplan> counterplanList = counterplanService.selectBatchIds(ids);
        for(int i = 0;i<counterplanList.size();i++){
            this.counterplanDao.setStatus(counterplanList.get(i).getId(), CounterplanStatus.APPROVE.getCode());
        }
        return SUCCESS_TIP;
    }

    /**
     * 审核未通过
     */
    @RequestMapping("/unapprove")
    @ResponseBody
    public Tip unapprove(@RequestParam(value = "ids[]") List<Integer> ids) {
        List<Counterplan> counterplanList = counterplanService.selectBatchIds(ids);
        for(int i = 0;i<counterplanList.size();i++){
            this.counterplanDao.setStatus(counterplanList.get(i).getId(), CounterplanStatus.UNAPPROVE.getCode());
        }
        return SUCCESS_TIP;
    }

    public static Method getGetMethod(Class objectClass, String fieldName) {
        StringBuffer sb = new StringBuffer();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString());
        } catch (Exception e) {
        }
        return null;
    }

    public static String invokeGet(Object o, String fieldName) {
        Method method = getGetMethod(o.getClass(), fieldName);
        try {
            return method.invoke(o, new Object[0]).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
